<template>
  <view class="setting">
    <nut-watermark :z-index="999" :content="userInfo.c_user_name"></nut-watermark>
    <nut-form
      ref="formRef"
      :model-value="params"
      :rules="rules"
    >
      <nut-form-item label="旧密码" label-align="center" prop="old_password"
      required>
        <nut-input v-model="params.old_password" placeholder="请输入旧密码" type="password"/>
      </nut-form-item>
      <nut-form-item label="新密码" label-align="center" prop="password"
      required>
        <nut-input v-model="params.password" placeholder="请输入新密码"  type="password"/>
      </nut-form-item>
    </nut-form>
    <view class="loginBtn">
      <nut-button type="success" block color="linear-gradient(to right, #ff6034, #ee0a24)" @click="changePwd">确认修改</nut-button>
    </view>
  </view>
</template>

<script setup>
import './index.scss';
import { reactive, ref } from 'vue';
import Taro, {useDidShow} from '@tarojs/taro'
import { My } from '@nutui/icons-vue-taro'
import JSEncrypt from 'jsencrypt';
import {getPublicKey, update_oneself_user_password} from '../../https/api'

const userInfo = ref({})
const formRef = ref(null)
const params = reactive({
    "old_password":'',
    "password": '',
    "private_key_id":''
   
})
const validatePass = (value) => {
  if( /^(?![0-9]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,}$/.test(value)) {
    return Promise.resolve()
  } else {
    return Promise.reject('密码包含字母和数字且长度不小于6')
  }
}
const rules = {
  old_password: [
      { required: true, message: '请输入旧密码' },
  ],
  password: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      {  validator: validatePass,  message: '新密码至少六个字符', },
  ],
}
const encryptWithPublicKey = (data, publicKey) => {
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(publicKey);
      return encrypt.encrypt(data);
}
const changePwd = () => {
  formRef.value?.validate().then(({ valid, errors }) => {
    if (valid) {
      getPublicKey().then(res => {
          params.private_key_id = res.data.private_key_id
          update_oneself_user_password({
              old_password: encryptWithPublicKey(params.old_password, res.data.public),
              password: encryptWithPublicKey(params.password, res.data.public),
              private_key_id: params.private_key_id
          }).then(reslute => {
              if(reslute.code == '1000') {
                Taro.removeStorage({
                  key: 'token',
                })
                Taro.removeStorage({
                  key: 'userInfo',
                })
                Taro.reLaunch({
                  url: '/pages/login/index'
                })
              }
          })
      })
    } else {
      console.warn('error:', errors)
    }
  })
}
useDidShow(() => {
  var userInfoSync = Taro.getStorageSync('userInfo')
  userInfo.value = userInfoSync ? JSON.parse(userInfoSync) : {}
  console.log(userInfo.value)
})
</script>

<style>
</style>